import React, { Component } from 'react'
import request from '@/utils/request';

import {
    DeleteOutlined,
    DownloadOutlined,
    EditOutlined,
    EyeOutlined,
    InteractionOutlined,
    PlusCircleFilled,
} from '@ant-design/icons';

import {
    Input,
    Button,
    notification,
    Row,
    Col,
    Pagination,
    Empty,
    Tooltip,
    Popconfirm,
    Table,
    Badge,
    Spin,
} from 'antd';
import NoData from '@/components/NoData';
import Styles from '../style.less'
import { getWordvecsList, getWordvec, getWordvecFiles, deleteWordvec, deleteWordvecDataset, wordvecTrain, wordvecTest } from '@/services/resource';
import AddWordvec from './components/addWordvec'
import UploadFiles from './components/uploadFiles'
import Detail from './components/detail'
import { createAndDownloadFile } from '@/utils/utils'
import { baseUrl } from '@/utils/config.js'
import WebSocket from '@/utils/webSocket'

const { Search } = Input;
const { TextArea } = Input;

class Vector extends Component {

    constructor(props) {
        super(props);
        this.state = {
            Heights: '',// 高度
            isLoading: true,// 列表加载
            wordvecsList: [],
            wordvecsSearchVal: '',//词向量查询内容
            wordvecName: '',
            wordvecId: '',
            wordvecType: '',// 0 词向量 1 语料
            wordvecInfo: [],
            isShowAddWordvecModel: false,
            isShowUploadModel: false,
            isShowDetail: false,
            pageNum: 1,
            pageSize: 5,
            total: 0,
            testLoading: false,
            wordvecResult: {},//训练结果
            testResult: '',//测试结果
            testKey: '',//测试词语
        };
    }

    componentDidMount() {
        const Heights = document.getElementById("contentBox").offsetHeight;
        this.setState({ Heights, }, () => {
            this.queryWordvecsList();
        });
    }


    // 获取词向量列表
    queryWordvecsList() {
        const { wordvecsSearchVal, wordvecId, wordvecType } = this.state;
        getWordvecsList({ wordvecName: wordvecsSearchVal }).then(res => {
            if (res.retCode === '0') {
                if (res.data.length) {
                    this.setState({ wordvecsList: res.data, wordvecId: wordvecId || res.data[0].wordvecId, wordvecType: wordvecType === '' ? res.data[0].sourceType : wordvecType, wordvecsSearchVal, }, () => { this.queryWordvecInfo() });
                } else {
                    this.setState({ wordvecsList: res.data, wordvecId: '', wordvecType: '', isLoading: false, wordvecsSearchVal, });
                }
            }
        })
    }
    //获取某个词向量下的文件  && 训练情况
    queryWordvecInfo() {
        const { wordvecId, wordvecType, pageNum, pageSize } = this.state;
        wordvecType == 1 && getWordvecFiles(wordvecId, wordvecType).then(res => {
            if (res.retCode === '0') {
                this.setState({ wordvecInfo: res.data, isLoading: false, });
            }
        })
        getWordvec(wordvecId).then(res => {
            if (res.retCode === '0') {
                this.setState({ wordvecResult: res.data, isLoading: false, });
            }
        })
    }
    // 新增/编辑 词向量
    onAddWordvec(isShowAddWordvecModel, key, wordvecName, backKey) {
        !isShowAddWordvecModel && this.queryWordvecsList();
        if (key === 'add') {
            this.setState({ isShowAddWordvecModel, wordvecName: '' })
        } else {
            this.setState({ isShowAddWordvecModel, wordvecId: key, wordvecName })
        }
    }
    // 上传文件
    onUplodeFiles(isShowUploadModel) {
        this.setState({ isShowUploadModel }, () => { !isShowUploadModel && this.queryWordvecInfo() });
    }
    // 词向量列表点击切换
    wordveChange(wordvecId, wordvecType) {
        this.setState({ wordvecId, wordvecType, testResult: '', testLoading: false, testKey: '' }, () => { this.queryWordvecInfo() });
    }
    // 词向量列表搜索
    onSearch(wordvecsSearchVal) {
        this.setState({ wordvecsSearchVal, }, () => {
            this.queryWordvecsList();
        });
    }
    // 词向量详情
    onShowDetail(isShowDetail) {
        this.setState({ isShowDetail });
    }
    // 删除 词向量
    onDeleteItem(id) {
        deleteWordvec(id).then(res => {
            if (res.retCode === '0') {
                this.setState({ wordvecId: '' }, () => { this.queryWordvecsList(); });

            }
        })
    }
    // 训练 词向量
    wordvecTrainStart() {
        const { wordvecId, } = this.state;
        this.setState({ testLoading: true, });
        wordvecTrain(wordvecId).then(res => {
            if (res.retCode === '0') {
                notification['success']({
                    message: '操作成功',
                    key: '词向量训练开始',
                    description: `词向量训练开始`,
                });
            } else {
                this.setState({ testLoading: false })
            }
        });
        WebSocket('nlp_wordvec_train', (res, rws) => {
            notification['success']({
                message: '操作成功',
                key: '词向量训练成功',
                description: `词向量训练成功`,
            });
            this.setState({ testLoading: false }, () => { rws.close(); this.queryWordvecInfo(); })
        }, close => {

        }, error => {

        })
    }
    // 测试
    wordvecTestStart(text, that) {
        const { wordvecId, } = that.state;
        if (String(text)) {
            wordvecTest({ modelWordVectorId: wordvecId, text }).then(res => {
                if (res.retCode === '0') {
                    notification['success']({
                        message: '操作成功',
                        key: '词向量',
                        description: `词向量测试完成`,
                    });
                    this.setState({ testResult: res.data, })
                }
            })
        } else {
            notification['warning']({
                message: '警告',
                key: '词向量',
                description: `请输入测试文本`,
            });
        }
    }

    // 删除 词向量下数据集
    del(datasetId) {
        deleteWordvecDataset(datasetId).then(res => {
            if (res.retCode === '0') {
                notification['success']({
                    message: '操作成功',
                    key: '删除',
                    description: `删除成功`,
                });
                this.queryWordvecInfo()
            }
        })
    }
    // 翻页
    onPageChange(pageNum) {
        const { pageSize, } = this.state;
        this.setState({ pageNum }, () => { this.queryWordvecInfo() });
    }
    // 下载
    download() {
        const { wordvecId, } = this.state;
        getWordvecFiles(wordvecId, 0).then(res => {
            if (res.retCode === '0') {
                const data = res.data[0].datasetId;
                if (data) {
                    createAndDownloadFile(`${baseUrl}/nlp/wordvec/dataset/download/${data}`)
                } else {
                    notification['warning']({
                        message: '下载异常',
                        key: '下载异常',
                        description: `文件不存在`,
                    });
                }
            }
        })
    }

    render() {
        const { Heights, isLoading, testLoading, wordvecsList, wordvecId, wordvecType, wordvecName, wordvecInfo, wordvecResult, testResult, isShowAddWordvecModel, isShowUploadModel, isShowDetail, pageNum, pageSize, total, testKey } = this.state;
        const columns = [
            {
                title: '文件名',
                dataIndex: 'datasetName',
                width: 220,
            },
            {
                title: '是否分词',
                width: 220,
                render: record => {
                    return [<Badge status="default" text={`否(${record.partLevel == 1 ? '词级别' : '字级别'})`} />, <Badge status="success" text='是' />][record.participle - 0]
                },
            },
            {
                title: '上传时间',
                dataIndex: 'createTime',
                width: 100
            }, {
                title: '操作',
                width: 120,
                render: record => {
                    return (
                        <span className={Styles.tableOperate}>
                            <a type="link" size='small' onClick={_ => { createAndDownloadFile(`${baseUrl}/nlp/wordvec/dataset/download/${record.datasetId}`, record.dataSetName) }}>下载</a>
                            <Popconfirm title="确定删除数据集？" onConfirm={this.del.bind(this, record.datasetId)} >
                                <a type="link" size='small'>删除</a>
                            </Popconfirm>
                        </span>
                    );
                },
            },
        ];
        const TestColumns = [{
            title: '词',
            dataIndex: 'word',
        }, {
            title: '相似度',
            dataIndex: 'score',
        },]
        return <>
            <Row>
                <Col span={4} style={{ height: `${Heights - 160}px`, overflowY: 'auto' }} className={Styles.resource}>
                    <h5>词向量列表<Tooltip title="添加词向量"><PlusCircleFilled onClick={this.onAddWordvec.bind(this, true, 'add', '')} /></Tooltip></h5>
                    <div style={{ paddingRight: 16 }}><Search placeholder="搜索文本" onSearch={value => this.onSearch(value)} /></div>
                    <div className={Styles.lists} style={{ height: `${Heights - 240}px` }}>
                        {wordvecsList.length > 0 ? wordvecsList.map((val, i) => {
                            return (
                                <a key={i} className={wordvecId == val.wordvecId ? Styles.active : ''} onClick={this.wordveChange.bind(this, val.wordvecId, val.sourceType)} role='wordvec'>
                                    <InteractionOutlined />&nbsp;&nbsp;{val.wordvecName}
                                    <span role="delete">
                                        <Tooltip title="查看">
                                            <EyeOutlined onClick={this.onShowDetail.bind(this, true)} />
                                        </Tooltip>
                                        <Tooltip title="编辑">
                                            <EditOutlined
                                                onClick={this.onAddWordvec.bind(this, true, val.wordvecId, val.wordvecName)} />
                                        </Tooltip>
                                        <Tooltip title="删除">
                                            <Popconfirm title="确定删除标签？" onConfirm={this.onDeleteItem.bind(this, val.wordvecId)} >
                                                <DeleteOutlined />
                                            </Popconfirm>
                                        </Tooltip>
                                    </span>
                                </a>
                            );
                        })
                            : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        }
                    </div>
                </Col>
                <Col span={20} style={{ height: `${Heights - 160}px` }} className={Styles.resourceTable}>
                    {wordvecsList.length > 0 && <h5 id={wordvecId} style={{ marginBottom: 16 }}>
                        {
                            wordvecsList.map(val => { if (val.wordvecId === wordvecId) return val.wordvecName })
                        }&nbsp;
                        {wordvecResult.wordvecResult && (wordvecResult.wordvecResult > -4 || wordvecType != 1) && <div className={Styles.detailInfo}>
                            训练结果&nbsp;&nbsp;{wordvecResult.wordvecResult > -1 ? `${wordvecResult.wordvecResult} 词` : [<span style={{ color: 'rgba(24, 144, 255, 1)' }}>正在训练...</span>, <span style={{ color: 'rgba(24, 144, 255, 1)' }}>正在解析...</span>, <span style={{ color: 'red' }}>失败</span>][wordvecResult.wordvecResult + 3]} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {wordvecResult.updateTimeShort || '2019-01-01 00:00:00'} &nbsp;&nbsp;&nbsp;&nbsp;<DownloadOutlined onClick={this.download.bind(this)} />
                        </div>}
                    </h5>}
                    <div className={Styles.modelBox}>
                        {isLoading ? <div className="Spin"><Spin tip="数据加载中..." /></div> :
                            <>
                                {
                                    wordvecsList.length ? <>
                                        <main>
                                            {wordvecType == 1 ? <>
                                                <div>
                                                    <h4>
                                                        <span>训练文本</span>
                                                        <Button size='small' loading={testLoading || (wordvecResult.wordvecResult && (wordvecResult.wordvecResult == -2 || wordvecResult.wordvecResult == -3))} onClick={this.wordvecTrainStart.bind(this)} style={{ float: 'right', marginLeft: 8 }}>{`训练${testLoading ? '中' : ''}`}</Button>
                                                        <Button type="primary" onClick={this.onUplodeFiles.bind(this, true)} size='small' style={{ float: 'right' }}>上传文件</Button>
                                                    </h4>
                                                    <Table
                                                        bordered
                                                        size='small'
                                                        columns={columns}
                                                        dataSource={wordvecInfo}
                                                        rowKey={record => record.datasetId}
                                                        pagination={{ total, current: pageNum, onChange: this.onPageChange.bind(this) }}
                                                    />
                                                </div>
                                                {/* <NoData title={'请先上传词向量语料'} dec={'支持格式 .json .txt .doc .docx .zip'} btn={'语料'} callBack={this.onUplodeFiles.bind(this, true)} /> */}
                                            </> : null
                                            }
                                            <div>
                                                <h4>
                                                    <span>测试</span>
                                                    <Search disabled={wordvecResult.wordvecResult > -1 ? false : true} placeholder="测试词" value={testKey} enterButton="测试" size="small" onSearch={val => { this.wordvecTestStart(val, this) }} className={Styles.testInput} onChange={e => { this.setState({ testKey: e.target.value }) }} />
                                                </h4>
                                                <section>
                                                    {testResult.length ?
                                                        <Row gutter={16}>
                                                            <Col span={12}>
                                                                <Table
                                                                    bordered
                                                                    size='small'
                                                                    columns={TestColumns}
                                                                    dataSource={testResult.filter((val, i) => i < 5)}
                                                                    rowKey={record => record.score}
                                                                    pagination={false}
                                                                />
                                                            </Col>
                                                            <Col span={12}><Table
                                                                bordered
                                                                size='small'
                                                                columns={TestColumns}
                                                                dataSource={testResult.filter((val, i) => i > 4)}
                                                                rowKey={record => record.score}
                                                                pagination={false}
                                                            /></Col>
                                                        </Row>
                                                        :
                                                        <div className={Styles.texts}>
                                                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={testResult === '' ? '请在右上方的的输入框内输入关键词，并点击【测试】' : '无数据'} className={Styles.empty} />
                                                        </div>
                                                    }
                                                </section>
                                            </div>
                                        </main>
                                    </> : <div style={{ marginTop: 200 }}><Empty /></div>
                                }
                            </>
                        }
                    </div>
                </Col>
            </Row>
            {isShowAddWordvecModel && <AddWordvec wordvecName={wordvecName} wordvecId={wordvecId} isShowAddWordvecModel={isShowAddWordvecModel} callBack={this.onAddWordvec.bind(this, false, wordvecId, wordvecName)} />}
            {isShowUploadModel && <UploadFiles isShowUploadModel={isShowUploadModel} wordvecType={wordvecType} wordvecId={wordvecId} callBack={this.onUplodeFiles.bind(this)} />}
            {isShowDetail && <Detail isShowDetail={isShowDetail} wordvecId={wordvecId} callBack={this.onShowDetail.bind(this)} />}
        </>;
    }
}

export default Vector
